#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
import urllib
from selenium.webdriver.support.ui import WebDriverWait
import urlparse
import logging
from esr_parser.core import get_item_id
from esr_parser.exceptions import PageEndError
from esr_parser.utils import func
from esr_parser.models import RankingScreenShot
import time
logger = logging.getLogger(__name__)


class Order(object):
    general = ''
    popular = '_deal'
    sales = '_credit'
    pricing_asc = 'price'
    pricing_desc = '_price'


class Rank_Task(object):
    driver = None

    def __init__(self, driver, keyword, order_by='general', tm_only=False, limit=90):
        self.keyword = keyword
        self.limit = limit
        self.driver = driver
        self.order_by = getattr(Order, order_by)
        self.tm_only = tm_only
        self.name = u"mobile_{}_{}_{}".format(keyword, order_by, tm_only)

    def close(self):
        self.driver.close()
        self.driver.quit()

    @func.auto_retry(3)
    def process(self):
        keyword = self.keyword
        result_items = []
        result_right_items = []
        result_bottom_items = []
        retry = 0
        self.search_items()
        items = []

        name = self.name
#        screenshot = self.driver.get_screenshot_as_png()
#        RankingScreenShot.create(name=name, screenshot=screenshot)

        while len(items) < self.limit:
            try:
                items += self.parse_page()
                self.next_page()
            except PageEndError:
                break

        return items

    search_page = 'http://s.m.taobao.com/h5?q={}'

    @func.auto_retry(3)
    def search_items(self):
        logger.debug('start search items')

        page_url = self.search_page.format(
            urllib.quote_plus(self.keyword.encode('utf-8')))
        self.driver.get(page_url)

        if self.tm_only:
            self.driver.execute_script("$('[data-value=tab_mall]').trigger('tap')")
        self.driver.execute_script("$('.sort[data-value=_sale]').trigger('tap')")
        time.sleep(5)

    def current_item_size(self):
        return len(self.driver.find_elements_by_css_selector('.mark .list-item'))

    @func.auto_retry(3)
    def load_page(self):
        pass

    def next_page(self):
        driver = self.driver
        page_info = driver.find_element_by_css_selector('.J_PageNavMain').text
        current_page, max_page = page_info.split('/')
        max_page, current_page = int(max_page), int(current_page)
        if current_page >= max_page:
            raise PageEndError()
        script = '''$('.page-container').remove(); $('.J_PageNext').trigger('tap')'''
        self.driver.execute_script(script)

        WebDriverWait(self.driver, 5).until(lambda x: bool(
            self.driver.find_elements_by_css_selector('.page-container')))

    @func.auto_retry(3)
    def parse_page(self, meta={}):
        logger.debug('parse page')
        driver = self.driver
        items = driver.find_elements_by_css_selector('.list-item')

        items = self.parse_items(items)
        return items

    @func.auto_retry(3)
    def parse_items(self, items, meta={}):
        result = []
        for index, item in enumerate(items):
            item_info = {}
            item_info['page_set'] = index
            item_info['page_num'] = 1
            item_info['pro_name'] = item.find_element_by_css_selector(
                '.d-title').text
            paid_elem = item.find_elements_by_css_selector('.d-num .font-num')
            item_info['month_pays'] = paid_elem and paid_elem[0].text or None
            item_info['price'] = item.find_element_by_css_selector(
                '.d-price .font-num').text
            item_info['pro_url'] = item.find_element_by_css_selector(
                '.p a').get_attribute('href')
            img_elem = item.find_element_by_css_selector('.p-pic')
            item_info['pro_img_url'] = img_elem.get_attribute('dataimg') or img_elem.get_attribute('src')
            urlinfo = urlparse.urlparse(item_info['pro_url'])
            params = dict(urlparse.parse_qsl(urlinfo.query))


            if item.find_elements_by_css_selector('.c-icon-pt'):
                item_info['is_tm'] = True
            else:
                item_info['is_tm'] = False


            if item.find_elements_by_css_selector('.c-icon-p4p'):
                item_info['extension_type'] = 1
            else:
                item_info['extension_type'] = 0

            try:
                item_info['auction_num_id'] = get_item_id(item_info['pro_url'])
            except:
                item_info['auction_num_id'] = None

            item_info.update(meta)

            result.append(item_info)
        return result



